package com.example.javascaffold.utils;

import com.example.javascaffold.exception.ParamException;
import com.example.javascaffold.exception.ResultException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


/**
 * 返回的结构
 * @author song
 * @date 11:35 2022/2/18
 * @param 
 * @return 
 * @other
**/
@ApiModel(value = "返回结果")
@Slf4j
@Data
public class Ret<T> {

    @ApiModelProperty(value = "返回消息", example = "请求成功")
    private String msg;

    @ApiModelProperty(value = "状态码", example = "1000")
    private Integer code;

    @ApiModelProperty(value = "返回数据", example = "执行完毕")
    private T data;
    
    /**
     * 静态方法 设置 data值
     * @author song
     * @date 15:17 2022/2/18
     * @param 
     * @return 
     * @other
    **/
    public static <T> Ret<T> data(T data) {
        Ret<T> ret = new Ret<>();
        ret.data = data;
        return ret;
    }

    /**
     * 静态方法 执行成功
     * @author song
     * @date 4:51 下午 2022/2/19
     * @param
     * @return
     * @other
    **/
    public static <T> void success(Ret<T> ret) {
        ret.setCode(200);
        ret.setMsg("执行成功");
    }
    
    /**
     * 静态方法 执行失败
     * @author song
     * @date 4:54 下午 2022/2/19
     * @param 
     * @return 
     * @other
    **/
    public static <T> void fail(Ret<T> ret) {
        ret.setCode(500);
        ret.setMsg("执行失败");
    }

    /**
     * 静态方法 执行失败 Exception
     * @author song
     * @date 4:54 下午 2022/2/19
     * @param
     * @other
     **/
    public static <T> void fail(Ret<T> ret, Exception e) {
        if (e instanceof ParamException) {
            ret.setMsg("参数异常: " + e.getMessage());
            ret.setCode(501);
        } else if (e instanceof ResultException) {
            ret.setMsg("执行异常: " + e.getMessage());
            ret.setCode(502);
        } else {
            ret.setMsg(e.getMessage());
            ret.setCode(500);
        }
    }


}
